package com.yk.fs.service.hadoop.impl;

import com.yk.fs.model.Icon;
import com.yk.fs.model.NodeModel;
import com.yk.fs.service.hadoop.api.IHadoopService;
import com.yk.fs.util.HdfsUtil;
import org.apache.hadoop.fs.FileStatus;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Limit on 2017/9/8.
 */
@Service("hadoopService")
public class HadoopServiceImpl implements IHadoopService {
   private HdfsUtil hdfsUtil=new HdfsUtil();

    @Override
    public List<NodeModel> queryChildren(String current) {

        List<NodeModel> nodeModels=new ArrayList<>();
        String parent=current;
        if(parent.equals("#"))
            parent="/";
        for(FileStatus status:this.hdfsUtil.queryChildrenFileStatus(parent)){
            nodeModels.add(this.buildNode(status,current,parent));
        }
        return nodeModels;
    }

    @Override
    public NodeModel createNode(String current,String parent) {

        if(this.hdfsUtil.createDir(current)) {
            FileStatus status=this.hdfsUtil.queryCurrentFileStatus(current);
            return this.buildNode(status,current,parent);
        }else
            return null;
    }

    @Override
    public NodeModel deleteNode(String current,String parent) {

        FileStatus status=this.hdfsUtil.queryCurrentFileStatus(current);
        NodeModel model=this.buildNode(status,current,parent);
        return (this.hdfsUtil.deleteDir(current))? model:null;
    }


    private NodeModel buildNode(FileStatus status,String current,String parent){
        NodeModel model=new NodeModel();
        model.setParent(current);
        model.setText(status.getPath().getName());
        if(status.isDirectory()){
            model.setChildren(true);
            model.setIcon(Icon.FOLDER_ICON.toString());
            model.setId(parent+status.getPath().getName()+"/");
        }else{
            model.setChildren(false);
            model.setIcon(Icon.FILE_ICON.toString());
            model.setId(parent+status.getPath().getName());
        }
        return model;
    }
}
